<template>
    <div class="user-container">
        <el-descriptions
            class="margin-top"
            title="个人信息"
            :column="1"
            border
            style="width: 500px;margin: 20px auto;"
        >
            <template slot="extra">
                <el-button
                    type="primary"
                    size="small"
                    @click="dialog_visible = true"
                    >修改</el-button
                >
            </template>
            <el-descriptions-item>
                <template slot="label">
                    <i class="el-icon-user"></i>
                    用户名
                </template>
                {{ user_info ? user_info.username : "" }}
            </el-descriptions-item>
            <el-descriptions-item>
                <template slot="label">
                    <i class="el-icon-postcard"></i>
                    邮箱
                </template>
                {{ user_info ? user_info.email : "" }}
            </el-descriptions-item>
            <el-descriptions-item>
                <template slot="label">
                    <i class="el-icon-s-custom"></i>
                    角色
                </template>
                {{ user_info ? user_info.role : "" }}
            </el-descriptions-item>
        </el-descriptions>
        <el-dialog
            title="用户信息修改"
            :visible.sync="dialog_visible"
            width="500px"
            :close-on-click-modal="false"
            :center="true"
        >
            <UserForm @submit="handle_submit" />
        </el-dialog>
    </div>
</template>

<script>
import { mapState } from "vuex"
import UserForm from "@/components/UserForm"
import { change_user_info } from "@/api"

export default {
    components: {
        UserForm
    },
    computed: {
        ...mapState("user", ["user_info"])
    },
    data() {
        return {
            dialog_visible: false
        }
    },
    methods: {
        handle_submit(data) {
            if (data.newPassword === "") {
                delete data.newPassword
            }
            change_user_info(data).then(
                () => {
                    this.$store.commit("user/set_user_info", {
                        ...this.user_info,
                        username: data.username,
                        role: data.role
                    })
                    this.$message({
                        message: "用户信息修改成功",
                        type: "success"
                    })
                    this.dialog_visible = false
                },
                (err) => {
                    this.$message({
                        message: err,
                        type: "error"
                    })
                }
            )
        }
    }
}
</script>
